<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\api\bill;

use think\App;
use app\controller\property\Base;
use app\common\services\CacheService;
use app\validate\bill\BillBasicValidate;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\bill\BillCatalogRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class BillBasic extends Base
{
    protected $repository;

    public function __construct(App $app, BillBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    /**
     *  账单统计
     * @return mixed
     *
     * @author Amos
     * 2024-06-14 09:18
     */
    public function getStatistics(int $id)
    {
        if ($id > 0) {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            if (!$propertyBasicRepository->existsByUserId($id, $this->request->userId())) {
                return app('api_return')->error('权限不足');
            }
        }
        $where = $this->request->param(['month' => '']);
        $res = CacheService::create($this->request->propertyId)
            ->remember('bill_survey_property_' . $id . $where['month'], function () use ($id, $where) {
                return $this->repository->getStatistics($id, $where['month']);
            }, 180);
        return app('api_return')->success($res);
    }

    /**
     *  账单列表
     * @return mixed
     *
     * @author Amos
     * 2024-06-14 11:55
     */
    public function getBillList()
    {
        $where = $this->request->param([
            'contract_id' => '',
            'property_id' => '',
            'room_id' => '',
            'status' => '',
            'bill_type' => '',
            'year' => '',
            'month' => '',
            'is_type' => '',
            'keywords' => ''
        ]);
        [$page, $limit] = $this->getPage();
        $res = $this->repository->getApiList($where, $page, $limit, $this->request->propertyId);
        return app('api_return')->success($res);
    }

    public function addBill()
    {
        $param = $this->request->param([
            'is_type' => '',
            'cutoff_date' => '',
            'overdue_fine_fee' => '',
            'property_id' => '',
            'contract_id' => '',
            'room_id' => '',
            'other_fee' => [],
            'remark' => '',
        ]);
        $param['bill_type'] = 4;
        $param['month_time'] = date('Y-m');
        $param['number'] = $this->repository->generateBillNumber($param['property_id']);
        validate(BillBasicValidate::class)->scene('add')->check($param);
        if ($param['property_id'] > 0) {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            if (!$propertyBasicRepository->existsByUserId($param['property_id'], $this->request->userId())) {
                return app('api_return')->error('权限不足');
            }
        }
        $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId());
        return app('api_return')->success($res['id']);
    }

    /**
     * 账单编辑
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-14 14:21
     */
    public function editBill(int $id)
    {
        if (!$this->repository->exists($id)) {
            return app('api_return')->error('数据不存在');
        }
        $param = $this->request->param([
            'remark' => '',
        ]);
        validate(BillBasicValidate::class)->scene('edit')->check($param);
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('信息错误');
        }
        $res = $this->repository->editInfo($info, $param, $this->request->userId());
        return app('api_return')->success($res);
    }

    /**
     *  删除账单
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-14 14:25
     */
    public function delete(int $id)
    {
        if (!$this->repository->exists($id)) {
            return app('api_return')->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        $param = $this->request->param([
            'remark' => '',
        ]);
        if ($info['property_id'] > 0) {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            if (!$propertyBasicRepository->existsByUserId($info['property_id'], $this->request->userId())) {
                return app('api_return')->error('权限不足');
            }
        }
        $res = $this->repository->batchDelete([$id], $this->request->userId(), $param['remark']);
        if ($res) {
            return app('api_return')->success('删除成功');
        } else {
            return app('api_return')->error('删除失败');
        }
    }

    /**
     * 账单详情
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-06-14 14:38
     */
    public function detail(int $id)
    {
        if (!$this->repository->exists($id)) {
            return app('api_return')->error('数据不存在');
        }
        $info = $this->repository->getApiDetail($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        return app('api_return')->success($info);
    }


    /**
     * 账单明细
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-06-14 14:38
     */
    public function billCatalog(int $id)
    {
        if (!$this->repository->exists($id)) {
            return app('api_return')->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if ($info['property_id'] > 0) {
            /** @var PropertyBasicRepository $propertyBasicRepository */
            $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
            if (!$propertyBasicRepository->existsByUserId($info['property_id'], $this->request->userId())) {
                return app('api_return')->error('权限不足');
            }
        }

        /** @var BillCatalogRepository $billCatalogRepository */
        $billCatalogRepository = app()->make(BillCatalogRepository::class);
        $info = $billCatalogRepository->getApiBillIdDetail($id);
        return app('api_return')->success($info);
    }

    /**
     *  账单延期
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-15 11:38
     */
    public function postponeAdd(int $id)
    {
        $day = (int)$this->request->param('day');
        if ($day <= 0) {
            return $this->error('延期天数必须大于0');
        }
        if (!$this->repository->exists($id)) {
            return app('api_return')->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if (!in_array($info['status'], [2, 5, 8])) {
            return app('api_return')->error('此账单不支持此操作');
        }
        $res = $this->repository->batchPostponeBill([$id], $day, $this->request->userId());
        if ($res) {
            return app('api_return')->success('延期成功');
        } else {
            return app('api_return')->error('延期失败');
        }
    }

    /**
     * 作废账单
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-15 11:48
     */
    public function invalidAdd(int $id)
    {
        $remark = $this->request->param('remark', '');
        if (!$this->repository->exists($id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if (!in_array($info['status'], [1, 2, 5, 8])) {
            return app('api_return')->error('此账单不支持此操作');
        }
        $res = $this->repository->batchInvalidBill([$id], $this->request->userId(), $remark);
        if ($res) {
            return app('api_return')->success('作废成功');
        } else {
            return app('api_return')->error('作废失败');
        }
    }

    /**
     * 催缴提醒
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-17 19:26
     */

    public function urgeAdd(int $id)
    {
        if (!$this->repository->exists($id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if (!in_array($info['status'], [2, 5, 8])) {
            return app('api_return')->error('此账单不支持此操作');
        }
        $res = $this->repository->batchUrgeBill([$id], $this->request->userId());
        if ($res) {
            return app('api_return')->success('催缴成功');
        } else {
            return app('api_return')->error('催缴失败');
        }
    }

    /**
     * 账单审核
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-17 19:32
     */
    public function auditAdd(int $id)
    {
        if (!$this->repository->exists($id)) {
            return $this->error('数据不存在');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if (!in_array($info['status'], [1])) {
            return app('api_return')->error('此账单不支持此操作');
        }
        $res = $this->repository->batchAuditBill([$id], $this->request->userId());
        if ($res) {
            return app('api_return')->success('审核成功');
        } else {
            return app('api_return')->error('审核失败');
        }
    }

    /**
     *  确认收款
     * @param int $id
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-17 19:42
     */
    public function paymentAdd(int $id)
    {
        if (!$this->repository->exists($id)) {
            return $this->error('数据不存在');
        }
        $param = $this->request->param([
            'pay_method' => '',
            'pay_amount' => '',
            'remark' => '',
        ]);
        validate(BillBasicValidate::class)->scene('payment')->check($param);
        $info = $this->repository->get($id);
        if (!$info) {
            return app('api_return')->error('数据不存在');
        }
        if (!in_array($info['status'], [2, 3, 5, 8])) {
            return app('api_return')->error('此账单不支持此操作');
        }
        $res = $this->repository->paymentBill($info, $param, $this->request->userId());
        if ($res) {
            return app('api_return')->success('确认成功');
        } else {
            return app('api_return')->error('确认失败');
        }
    }


}